package com.ygqh.baby.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.utils.DateConvertUtils;

public class YgExceptionHandler {

	protected final Logger logger = Logger.getLogger(this.getClass());

	/** 基于@ExceptionHandler异常处理 */
	@ExceptionHandler
	@ResponseBody
	public JSONPObject execute(HttpServletRequest request, HttpServletResponse response, Exception ex) {
		String callback = request.getParameter("callback");
		// TODO
		StringBuilder sb = new StringBuilder();
		StackTraceElement[] st = ex.getStackTrace();
		for (StackTraceElement stackTraceElement : st) {
			String exclass = stackTraceElement.getClassName();
			String method = stackTraceElement.getMethodName();
			if (exclass.contains("com.ygqh.baby")) {
				sb.append(DateConvertUtils.formatDateTime(new Date()) + ":" + "[类:" + exclass + "]调用" + method + "时在第"
						+ stackTraceElement.getLineNumber() + "行代码处发生异常!异常类型:" + ex.getClass().getName() + "</br>");
			}
		}
		ex.printStackTrace();
		logger.error(sb.toString());
		return new JSONPObject(callback, Message.error(ex.getMessage()));
	}
}
